<template>
  <div class="list-content">
    <el-form :inline="true" :model="formInline" class="demo-form-inline" @submit.native.prevent>
      <el-form-item v-if="isMuilUnitUser">
        <el-select filterable @change="getStatis()" v-model="formInline.orgId" placeholder="请选择业主单位">
          <el-option
            v-for="item in orgOptions"
            :key="item.organizationId"
            :label="item.shortName"
            :value="item.organizationId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="formInline.time"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="util.intTimePickerOptions()"
          @change="getStatis()"
          >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button class="form-search-btn" type="primary" @click="getStatis()">查询</el-button>
      </el-form-item>
    </el-form>
    <el-row class="overview-wrap" :gutter="40" type="flex" justify="space-between">
      <span style="display:none;">{{freashStaticFlag}}</span>
      <el-col :span="12">
        <div class="item-wrap">
          <p class="item-value color-1">{{ staticObj.avgDoTime ||0 }}</p>
          <p class="item-title">隐患平均处理时长（小时）</p>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="item-wrap">
          <p class="item-value color-2">{{ staticObj.faultavgHandlerTime ||0}}</p>
          <p class="item-title">其中故障维修平均处理时长（小时）</p>
        </div>
      </el-col>
    </el-row>
    <el-row v-loading="loading">
      <el-col :span="24">
        <div class="grid-content">
          <div class="chart-heaad">隐患分析</div>  
          <el-row :gutter="20">
            <el-col :md="12">
              <div id="chart_HiddenDangerAnalysis_type" class="chart-content bg"></div>
            </el-col>
            <el-col :md="12">
              <div id="chart_HiddenDangerAnalysis_level" class="chart-content bg"></div>
            </el-col>
          </el-row>
          <el-row>
            <div id="chart_HiddenDangerAnalysis_trend" class="chart-content"></div>
            <div v-if="isMuilUnitUser" id="chart_HiddenDangerAnalysis_topTen" class="chart-content"></div>
          </el-row>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as Dao from '@/api/hiddenDanger'
import { getOrgList} from '@/api/org'
import util from '@/utils/util'

export default {
  name: 'HiddenDangerAnalysis',
  props:['param'],
  data () {
    return {
      freashStaticFlag:0,
      formInline: {
        orgId:this.$store.state.userinfo.isMuilUnitUser ? this.$store.state.userinfo.organizationIds : this.$store.state.userinfo.org.id,
        time:'',
      },
      util:util,
      tableData: [],//表格数据
      staticObj:{},//头部各状态个数统计
      isMuilUnitUser:this.$store.state.userinfo.isMuilUnitUser,
      accountName:this.$store.state.userinfo.accountName,
      orgOptions: [{organizationId: this.$store.state.userinfo.organizationIds,shortName: "全部业主单位"}],
      loading: false,
      colorList:[
                  '#70bbea','#5c90d2','#a58ad4','#f3b75e','#ea4f63',
                   '#16adc4','#9BCA63','#FAD860','#F3A43B','#60C0DD',
                   '#D7504B','#C6E579','#F4E001','#F0805A','#26C0C0'
                ]
    }
  },
  created:function() {
    //默认一个月
    let end = new Date();
    let start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
    this.formInline.time = [util.ilinkTimeformat.format(start, 'yyyy-MM-dd ')+'00:00:00', util.ilinkTimeformat.format(end, 'yyyy-MM-dd ')+'23:59:59']
    //绑定下拉框
    if(this.isMuilUnitUser){
      getOrgList({queryType: 0}).then((data)=>{
        this.orgOptions.push.apply(this.orgOptions,data.data);
      })
    }else{
      
    }
   this.getStatis()
  },
  methods: {
    getStatis() {
      let that = this
      that.loading = true
      //头统计
      Dao.getHiddenStatistics({
        orgIds: that.formInline.orgId,
        startTime: that.formInline.time?(that.formInline.time[0].split(' ')[0]+' 00:00:00'):'',
        endTime: that.formInline.time?(that.formInline.time[1].split(' ')[0]+' 23:59:59'):'',
      }).then((data)=>{
        that.loading = false
        $.extend(this.staticObj,data.data) 
        this.freashStaticFlag++
      })
      //隐患等级分布
      Dao.getHiddenGradeNumByStatus({
        orgIds: that.formInline.orgId,
        type: 2,
        status: 0,
        startTime: that.formInline.time?(that.formInline.time[0].split(' ')[0]+' 00:00:00'):'',
        endTime: that.formInline.time?(that.formInline.time[1].split(' ')[0]+' 23:59:59'):'',
      }).then((data)=>{
        that.loading = false
        let pieDate = [];
        $.each(data.data,(index,obj)=>{
          pieDate.push({
            name:obj.gradeName,
            value:obj.count,
            itemStyle:{ normal: { color: that.colorList[index] } }
          })
        })
        let option_echart = {
            title: {
                textStyle: { color: '#2F3444', fontSize: '16' },
                y: 'left',
                left: '15',
                top: '0',
                text: '隐患等级分布',
            },
            grid: {
                left: '3%',
                right: '3%',
                top: '35px',
                bottom: '30px'
            },
            tooltip: {
                trigger: 'item',
                formatter: "{b}: {c}({d}%)"
            },
            series: [{
                type: 'pie',
                radius: ['50%', '70%'],
                avoidLabelOverlap: true,
                label: {
                    formatter: "{b}: {c}({d}%)",
                    emphasis: {
                        show: true,
                        textStyle: {
                            fontSize: '20',
                            fontWeight: 'bold'
                        }
                    }
                },
                labelLine: {
                    normal: {
                        show: true
                    }
                },
                data: pieDate
            }]
        }
        that.$echarts.init(document.getElementById('chart_HiddenDangerAnalysis_level')).setOption(option_echart, true);
      })
      //隐患类型分布
      Dao.getHiddenGradeNumByStatus({
        orgIds: that.formInline.orgId,
        type: 1,
        status: 0,
        startTime: that.formInline.time?(that.formInline.time[0].split(' ')[0]+' 00:00:00'):'',
        endTime: that.formInline.time?(that.formInline.time[1].split(' ')[0]+' 23:59:59'):'',
      }).then((data)=>{
        that.loading = false
        let pieDate = [];
        $.each(data.data,(index,obj)=>{
          pieDate.push({
            name:obj.categoryName,
            value:obj.count,
            itemStyle:{ normal: { color: that.colorList[index] } }
          })
        })
        let option_echart = {
            title: {
                textStyle: { color: '#2F3444', fontSize: '16' },
                y: 'left',
                left: '15',
                top: '0',
                text: '隐患类型分布',
            },
            grid: {
                left: '3%',
                right: '3%',
                top: '35px',
                bottom: '30px'
            },
            tooltip: {
                trigger: 'item',
                formatter: "{b}: {c}({d}%)"
            },
            series: [{
                type: 'pie',
                radius: ['50%', '70%'],
                avoidLabelOverlap: true,
                label: {
                    formatter: "{b}: {c}({d}%)",
                    emphasis: {
                        show: true,
                        textStyle: {
                            fontSize: '20',
                            fontWeight: 'bold'
                        }
                    }
                },
                labelLine: {
                    normal: {
                        show: true
                    }
                },
                data: pieDate
            }]
        }
        that.$echarts.init(document.getElementById('chart_HiddenDangerAnalysis_type')).setOption(option_echart, true);
      })
      //隐患创建走势
      Dao.getHiddenCreateStatistics({
        orgIds: that.formInline.orgId,
        type: 0,
        startTime: that.formInline.time?(that.formInline.time[0].split(' ')[0]+' 00:00:00'):'',
        endTime: that.formInline.time?(that.formInline.time[1].split(' ')[0]+' 23:59:59'):'',
      }).then((data)=>{
        that.loading = false
        let xData = [];
        let yData = [];
        let yDataOther = [];
        $.each(data.data.dataCountList,(index,obj)=>{
          xData.push(obj.dayTime);
          yData.push(obj.count);
          yDataOther.push(obj.faultCount);
        })
        let option_echart = {
            legend:{
              show:true
            },
            title: {
                textStyle: { color: '#2F3444', fontSize: '16' },
                y: 'left',
                left: '15',
                top: '0',
                text: '隐患创建走势',
            },
            grid: {
                left: '3%',
                right: '3%',
                top: '35px',
                bottom: '30'
            },
            tooltip: {
                trigger: 'axis',
                formatter:function(params){
                  let _html = params[0].name+'</br>'
                  $.each(params,(index,obj)=>{
                    _html+=(obj.seriesName+'：' + obj.value+'</br>')
                  })
                  return _html
                },
                axisPointer: { // 坐标轴指示器，坐标轴触发有效
                    type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                }
            },
            xAxis: {
                type: 'category',
                axisTick: {
                    show: false
                },
                triggerEvent: true,
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: 'rgba(55, 139, 246, 0.8)',
                        width: 1, //这里是为了突出显示加上的
                    }
                },
                axisLabel: {
                    show: true,
                    textStyle: {
                        color: '#2F3444',
                        fontSize: 14
                    },
                    //interval:xInterval
                },
                //max:30,
                boundaryGap: true,
                data: xData
            },
            yAxis: {
                type: 'value',
                axisTick: {
                    show: false
                },
                //min:minLeavel,
                //max:maxLeavel,
                axisLine: {
                    show: false,
                },
                axisLabel: {
                    formatter: '{value}',
                    show: true,
                    textStyle: {
                        color: '#2F3444',
                        fontSize: 14
                    }
                },
                splitLine: {
                    lineStyle: {
                        color: 'rgba(55, 139, 246, 0.8)',
                        opacity: 0.7
                    }
                },
                axisPointer: {
                    snap: true
                },
                minInterval: 1
            },
            series: [{
                name: "故障维修",
                type: 'bar',
                stack: '隐患数量',
                barMaxWidth: '30',
                itemStyle: {
                    normal: {
                        color: '#FFB32D',
                    }
                },
                label: {
                    normal: {
                        show: false,
                        position: 'inside'
                    }
                },
               data: yData
            },{
                name: "其他隐患",
                type: 'bar',
                stack: '隐患数量',
                barMaxWidth: '30',
                itemStyle: {
                    normal: {
                        color: '#4CA4FE',
                    }
                },
                label: {
                    normal: {
                        show: false,
                        position: 'inside'
                    }
                },
               data: yDataOther
            }]
        }
        that.$echarts.init(document.getElementById('chart_HiddenDangerAnalysis_trend')).setOption(option_echart, true);
      })
      //隐患创建单位TOP10
      if(that.isMuilUnitUser){
        Dao.getHiddenOrgStatistics({
          orgIds: that.formInline.orgId,
          startTime: that.formInline.time?(that.formInline.time[0].split(' ')[0]+' 00:00:00'):'',
          endTime: that.formInline.time?(that.formInline.time[1].split(' ')[0]+' 23:59:59'):'',
          order: 0
        }).then((data)=>{
            that.loading = false
            let xData = []
            let yData = []
            let Mid = 0
            let Average = 0
            let Sum = 0
            let Min = 100
            let Max = 0
            $.each(data.data.list,(index,obj)=>{
              let _finishPercent = parseFloat(obj.count) 
              xData.push(obj.orgName)
              yData.push(_finishPercent)
              /* Sum+=_finishPercent
              if(Max<_finishPercent){
                Max=_finishPercent;
              } 
              if(Min>_finishPercent){
                Min=_finishPercent;
              } */ 
            })
            /* Min = Math.ceil(Min)
            Max = Math.ceil(Max)
            let l =  yData.length
            let n =  Math.floor(l/2)
            if (l%2==0){
                Mid = (yData[l/2-1]+yData[l/2])/2
            }else{
                Mid = yData[(l-1)/2]
            }
            Mid = Math.ceil(Mid)
            Average = l==0?0:( Math.ceil(Sum/l)) */
            //画图
            let option_echart = {
              title: {
                  textStyle: { color: '#2F3444', fontSize: '16' },
                  y: 'left',
                  left: '15',
                  top: '0',
                  text: '隐患创建单位TOP10',
              },
              grid: {
                  left: '55px',
                  right: '55px',
              },
              tooltip: {
                  trigger: 'axis',
                  formatter: "{b}<br/>隐患个数: {c}",
                  axisPointer: { // 坐标轴指示器，坐标轴触发有效
                      type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                  }
              },
              xAxis: {
                  type: 'category',
                  axisTick: {
                      show: false
                  },
                  triggerEvent: true,
                  axisLine: {
                    show: true,
                    lineStyle: {
                        color: 'rgba(105, 115, 125, 1)',
                        width: 1, //这里是为了突出显示加上的
                    }
                  },
                  axisLabel: {
                      show: true,
                      textStyle: {
                          color: 'rgba(95, 104, 132, 1)',
                          fontSize: 14
                      },
                      //interval:xInterval
                  },
                  boundaryGap: true,
                  data: xData
              },
              yAxis: {
                  type: 'value',
                  axisTick: {
                      show: false
                  },
                  //interval:1,
                  //min:Min,
                  //max:Max,
                  axisLine: {
                    show: true,
                    lineStyle: {
                        color: 'rgba(105, 115, 125, 1)',
                        width: 1, //这里是为了突出显示加上的
                    }
                  },
                  axisLabel: {
                      /* formatter:function(value){
                        if(value == Max){
                          return 'max'
                        }else if(value == Min){
                          return 'min'
                        }else if(value == Average){//Mid
                          return 'mid'
                        }else{
                          return ''
                        }
                      }, */
                      show: true,
                      textStyle: {
                          color: 'rgba(95, 104, 132, 1)',
                          fontSize: 14
                      }
                  },
                  splitLine: {
                      show:false
                  },
                  axisPointer: {
                      snap: true
                  }
              },
              series: [{
                  name: "隐患数量",
                  type: 'bar',
                  barMaxWidth: '128',
                  itemStyle: {
                    barBorderRadius:[4,4,0,0],
                    shadowColor: function(params) {
                        return that.colorList[params.dataIndex]
                    },
                    color: function(params) {
                        return that.colorList[params.dataIndex]
                    },
                  },
                  label: {
                    normal: {
                        show: false,
                        position: 'inside'
                    }
                  },
                  data: yData
              }]
            };
            that.$echarts.init(document.getElementById('chart_HiddenDangerAnalysis_topTen')).setOption(option_echart, true);
        })
      }
    },
  },
}
</script>
<style lang="scss" scoped>
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
    .chart-heaad{
      height:25px;
      line-height:25px;
      font-size:18px;
      font-weight:500;
      color:rgba(68, 107, 222, 1);
      -webkit-text-stroke:1px rgba(68, 107, 222, 1);
      text-stroke:1px rgba(68, 107, 222, 1);
    }
    .chart-content{
      margin-top: 20px;
      height: 354px;
      padding: 20px;
      &.bg{
        background:rgba(225,225,225,.2);
      }
      &.bd{
        border:1px solid rgba(225,225,225,1);
      }
      &.pd0{
        padding: 0;
      }
    }
    .chart-content-title{
      line-height: 65px;
      text-indent: 40px;
      font-size:16px;
      font-weight:bold;
      color: #2F3444;
      background:rgba(240,242,245,.5);
    }
  }
</style>